<template>
    <div>
        <el-container>
            <el-header>
                <el-row>
                    <el-col :span="12">
                        <el-upload
                                ref="upload"
                                action="/"
                                :show-file-list="false"
                                :on-change="importExcel"
                                :auto-upload="false"
                                style="margin-top: 40px;margin-left: 320px">
                            <el-button
                                    slot="trigger"
                                    icon="el-icon-upload"
                                    size="small"
                                    type="success">
                                导入Excel文件
                            </el-button>
                        </el-upload>
                    </el-col>
                    <el-col :span="12" >
                        <el-button type="primary" size="small" style="margin-top: 40px"
                                   @click="registerResidentExcel">下载模板</el-button>
                    </el-col>
                </el-row>
            </el-header>
            <el-main>
                <el-form :model="rrbData.form" ref="rrbForm" label-width="100px" v-loading="rrbData.loading" class="demo-dynamic">
                    <el-container>
                        <el-main>
                            <div style="height: 400px">
                                <el-scrollbar
                                        wrapStyle="color:'#fff';fontSize:'16px';"
                                        viewStyle="color:'#fff';fontSize:'16px';"
                                        :native="false"
                                        :noresize="true"
                                        tag="div">
                                    <div>
                                        <div v-for="(item,index) in rrbData.form.data"
                                             :key="index"
                                             :class="{bc2:index%2===0,bc:index%2===1}">
                                            <el-divider content-position="left">{{'居民' + index}}</el-divider>
                                            <el-form-item
                                                    label="用户名"
                                                    :prop="'data.'+index+'.username'"
                                                    :rules="[
                                            { required: true, message: '请输入用户名', trigger: 'blur' }
                                        ]">
                                                <el-input type="text" v-model="item.username" style="width: 160px"></el-input>
                                            </el-form-item>
                                            <el-form-item
                                                    label="密码"
                                                    :prop="'data.'+index+'.password'"
                                                    :rules="[
                                            { required: true, message: '请输入密码', trigger: 'blur' }]">
                                                <el-input type="text" v-model="item.password" style="width: 160px"></el-input>
                                                <el-button type="danger" @click.prevent="removeUser(index)">删除</el-button>
                                            </el-form-item>
                                        </div>
                                    </div>
                                </el-scrollbar>
                            </div>
                        </el-main>
                        <el-footer>
                            <el-form-item>
                                <el-button type="primary" @click="registerResidentBatch">批量注册居民</el-button>
                                <el-button type="success" @click="addUser">新增用户项</el-button>
                                <el-button type="info" @click="resetForm">重置</el-button>
                            </el-form-item>
                        </el-footer>
                    </el-container>
                </el-form>
            </el-main>
        </el-container>
    </div>
</template>
<script>
    import XLSX from 'xlsx'
    export default {
        name: "registerResigentBatch",
        data() {
            return {
                rrbData:{
                    loading: false,
                    form:{
                        data:[{
                            username:"",
                            password:"123456"
                        }]
                    }
                },
            };
        },
        methods: {
            registerResidentBatch() {
                const _this = this;
                this.$refs.rrbForm.validate((valid) => {
                    if (valid) {
                        _this.rrbData.loading=true;
                        let identityAuthVo={
                            userVoList:_this.rrbData.form.data
                        };
                        this.postRequestJson("/identityauth/regresidentbatch",identityAuthVo)
                            .then(resp =>{
                                if (resp && resp.data && resp.data.code === '200') {
                                    _this.rrbData.loading=false;
                                    //清空数据
                                    _this.rrbData.form.data=[{
                                        username:"",
                                        password:"123456"
                                    }];
                                }else {
                                    _this.rrbData.loading=false;
                                }
                            })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            resetForm() {
                this.$refs.rrbForm.resetFields();
            },
            removeUser(index){
                if (index !== -1) {
                    this.rrbData.form.data.splice(index, 1)
                }
            },
            addUser() {
                this.rrbData.form.data.push({
                    username:"",
                    password:"123456",
                });
            },
            importExcel(file) {
                const _this=this;
                // let file = file.files[0] // 使用传统的input方法需要加上这一步
                const types = file.name.split('.')[1]
                const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv'].some(item => item === types)
                if (!fileType) {
                    alert('格式错误！请重新选择')
                    return
                }
                this.file2Xce(file).then(tabJson => {
                    if (tabJson && tabJson.length > 0) {
                        this.xlsxJson = tabJson
                        console.log(this.xlsxJson[0].sheet[0]);
                        this.xlsxJson[0].sheet.forEach((item)=>{
                            _this.rrbData.form.data.push({
                                username:item['用户名'],
                                password:item['密码'],
                            });
                        })
                        // xlsxJson就是解析出来的json数据,数据格式如下
                        // [
                        //   {
                        //     sheetName: sheet1
                        //     sheet: sheetData
                        //   }
                        // ]
                    }
                })
            },
            file2Xce(file) {
                return new Promise(function(resolve) {
                    const reader = new FileReader()
                    reader.onload = function(e) {
                        const data = e.target.result
                        this.wb = XLSX.read(data, {
                            type: 'binary'
                        })
                        const result = []
                        this.wb.SheetNames.forEach((sheetName) => {
                            result.push({
                                sheetName: sheetName,
                                sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
                            })
                        })
                        resolve(result)
                    }
                    reader.readAsBinaryString(file.raw)
                    // reader.readAsBinaryString(file) // 传统input方法
                })
            },
            registerResidentExcel(){
                const _this=this;
                this.getRequest("/download/registerResidentExcel")
                    .then(resp =>{
                        if (resp && resp.data) {
                            console.log(resp.headers);
                            _this.$message.success("下载成功");
                        }
                    })
            }
        }
    }
</script>
<style  scoped>
    .bc {
        background-color: white;
    }
    .bc2 {
        background-color: #F2F6FC;
    }

</style>